package org.whb.basic.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.whb.basic.constant.LoginConstant;
import org.whb.basic.exception.BusinessException;
import org.whb.basic.service.IVerificationCodeService;
import org.whb.basic.util.SmsUtils;
import org.whb.basic.util.StrUtils;
import org.whb.user.domain.User;
import org.whb.user.mapper.UserMapper;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class VerificationCodeServiceImpl implements IVerificationCodeService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Override
    public void sendSmsCode(Map<String, String> phone) {
        //获取电话号码
        String phoneNum = phone.get("phone");
        String type = phone.get("type");
        //一、基础判断
        //1、判断电话号码是否为空
        if(StringUtils.isEmpty(phoneNum)){
            throw new BusinessException("请填写电话号码");
        }

        //二、验证码判断
        //1、判断redis中的验证码是否已经过期
        if(type.equals("register")){ //手机注册验证码
            //2、判断号码是否已经注册过
            User user = userMapper.loadByPhone(phoneNum);
            if(user!=null){//说明该用户已经注册过
                throw new BusinessException("你的手机号已经注册过，请直接登录");
            }
            String redisKey= LoginConstant.PHONE_REGISTER+phoneNum;
            getCode(redisKey);
        }else if (type.equals("binder")){ //微信绑定验证码
            String redisKey= LoginConstant.WX_BINDER+phoneNum;
            getCode(redisKey);
        }


    }

    private void getCode(String redisKey){
        Object oldRedisValue = redisTemplate.opsForValue().get(redisKey);
        String code = "";
        if(oldRedisValue!=null){ //1.1 该手机号的验证码还未过期
            //1.1.1 判断是否过了一分钟
            Long time = System.currentTimeMillis()-Long.valueOf(oldRedisValue.toString().split(":")[1]);
            if(time<=1*60*1000){//时间小于一分钟
                throw new BusinessException("请一分钟后再进行尝试");
            }
            //1、时间过了一分钟
            code=oldRedisValue.toString().split(":")[0];
        }else{//1.2 验证码已经过期了或者还没有注册过
            //生成新的验证码
            code = StrUtils.getComplexRandomString(4);
        }
        //三、存放验证码并重置过期时间
        String newRedisValue = code+":"+System.currentTimeMillis();
        redisTemplate.opsForValue().set(redisKey, newRedisValue, 3, TimeUnit.MINUTES);
        //SmsUtils.sendSms(phoneNum, "你的验证码是："+code);
        System.out.println("您的验证码是："+code+",验证码三分钟内有效");
    }
}
